package com.gensdai.leliang.activity;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.adapter.NumericWheelAdapter;
import com.bigkoo.pickerview.lib.WheelView;
import com.gensdai.leliang.R;
import com.gensdai.leliang.base.BaseActivityNoAbs;
import com.gensdai.leliang.common.bean.ProvinceJsonBean;
import com.gensdai.leliang.dialog.Upload;
import com.gensdai.leliang.entity.User;
import com.gensdai.leliang.json_base.json_base;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.gensdai.leliang.utils.GetJsonDataUtil;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/9/11.
 */

public class Set_yunyu_xq extends BaseActivityNoAbs implements View.OnClickListener {

    @BindView(R.id.ui_title)
    TextView uiTitle;
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.right_tv)
    TextView rightTv;
    @BindView(R.id.date)
    TextView date;
    @BindView(R.id.state_title)
    TextView stateTitle;
    @BindView(R.id.set_time)
    LinearLayout setTime;
    @BindView(R.id.by_recompose)
    TextView byRecompose;
    @BindView(R.id.set_byz_time)
    LinearLayout setByzTime;
    @BindView(R.id.hy_recompose)
    TextView hyRecompose;
    @BindView(R.id.set_hyz_time)
    LinearLayout setHyzTime;
    @BindView(R.id.hy_state)
    LinearLayout hyState;
    @BindView(R.id.set_bb_name)
    EditText setBbName;
    @BindView(R.id.set_shengri)
    TextView setShengri;
    @BindView(R.id.set_bb_weman)
    RadioButton setBbWeman;
    @BindView(R.id.set_bb_man)
    RadioButton setBbMan;
    @BindView(R.id.set_bb_tz)
    TextView setBbTz;
    @BindView(R.id.set_bb_sg)
    TextView setBbSg;
    @BindView(R.id.set_bb_info)
    LinearLayout setBbInfo;
    @BindView(R.id.user_state)
    TextView userState;
    @BindView(R.id.bbsr_recompose)
    TextView bbsrRecompose;
    @BindView(R.id.set_yybb_time)
    LinearLayout setYybbTime;
    @BindView(R.id.chakan_yuchanqi)
    TextView chakanYuchanqi;
    @BindView(R.id.chakan_bb_shengri)
    TextView chakanBbShengri;

    private Upload up;
    SharedPreferences share;
    SharedPreferences.Editor ed;
    int mYear, mMonth, mDay;
    private int state = -1; // 1. 第一次进入，选择宝宝生日 2. 第一次进入，选择预产期 3. 选择待孕中 4. 选择第二次进入，选择预产期  5.设置宝宝详情信息
    private String bb_sex = "-1";  //0 女孩  1 男孩
    private boolean or = false; //false 代表选择体重 true 代表选择身高

    final int DATE_DIALOG = 100;
    private User user;
    private final int JIECHU = 3;// 设置状态
    private final int CHAXUN = 2;// 查询详情
    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case JIECHU:
                    up.dismiss();
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            if (state == 1) {
                                state = 5;
                                setTime.setVisibility(View.GONE);
                                setYybbTime.setVisibility(View.VISIBLE);
                                chakanBbShengri.setText("宝宝生日：" + mYear + "年" + (mMonth + 1) + "月" + mDay + "日");
                                setShengri.setText(+mYear + "年" + (mMonth + 1) + "月" + mDay + "日");
                            } else
                                Set_yunyu_xq.this.finish();
                        } else {

                        }
                        Toast.makeText(
                                Set_yunyu_xq.this,
                                new JSONObject((String) msg.obj)
                                        .getString("message"),
                                Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case CHAXUN:
                    up.dismiss();
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            user = (User) new json_base().JsonUserBBInfo(new JSONObject((String) msg.obj));
                            if (user == null) {
                                return;
                            }
                            if (!user.getBabyNickname().equals("")) {
                                setBbName.setText(user.getBabyNickname());
                            }
                            setShengri.setText(user.getBabyBirthday());
                            if ((bb_sex.equals("1") && user.getBabySex().equals("小王子")) || (bb_sex.equals("-1") && user.getBabySex().equals("小王子"))) {
                                setBbMan.setChecked(true);
                                bb_sex = "1";
                            }
                            setBbTz.setText(user.getBabyBirthHeight());
                            setBbSg.setText(user.getBabyBirthWeight());
                            chakanYuchanqi.setText("预产期：" + user.getBabyExceptedBirthday());
                            chakanBbShengri.setText("宝宝生日：" + user.getBabyBirthday());
                        } else {
                            if (state == 1 || state == 2) return;
                            Toast.makeText(
                                    Set_yunyu_xq.this,
                                    new JSONObject((String) msg.obj)
                                            .getString("message"),
                                    Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.set_yunyu_xq);
        ButterKnife.bind(this);
        init();

    }

    @Override
    protected void onStart() {
        super.onStart();
        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("userNo", share.getString("userno", ""));
        chaxunAPI(loginParams);
    }

    /**
     * 初始化
     */
    private void init() {

        final Calendar ca = Calendar.getInstance();
        mYear = ca.get(Calendar.YEAR);
        mMonth = ca.get(Calendar.MONTH);
        mDay = ca.get(Calendar.DAY_OF_MONTH);
        uiTitle.setText(getIntent().getStringExtra("title"));
        state = Integer.parseInt(getIntent().getStringExtra("state"));
        if (getIntent().hasExtra("bb_sex")) {
            bb_sex = getIntent().getStringExtra("bb_sex");
        }
        if (bb_sex.equals("1")) {
            setBbMan.setChecked(true);
        }
        switch (state) {
            case 1:
                rightTv.setVisibility(View.VISIBLE);
                rightTv.setTextSize(15f);
                setTime.setVisibility(View.VISIBLE);
                date.setText(mYear + "年" + (mMonth + 1) + "月" + mDay + "日");
                break;
            case 2:
                rightTv.setVisibility(View.VISIBLE);
                rightTv.setTextSize(15f);
                stateTitle.setText("您的预产期");
                setTime.setVisibility(View.VISIBLE);
                date.setText(mYear + "年" + (mMonth + 1) + "月" + mDay + "日");
                break;
            case 3:
                setByzTime.setVisibility(View.VISIBLE);
                break;
            case 4:
                stateTitle.setText("您的预产期");
                setHyzTime.setVisibility(View.VISIBLE);
                rightTv.setVisibility(View.VISIBLE);
                break;
            case 5:
                setYybbTime.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
        rightTv.setText("保存");

        share = getSharedPreferences("User", MODE_PRIVATE);
        ed = share.edit();
        up = new Upload(this);

        back.setOnClickListener(this);
        date.setOnClickListener(this);
        rightTv.setOnClickListener(this);
        byRecompose.setOnClickListener(this);
        hyRecompose.setOnClickListener(this);
        bbsrRecompose.setOnClickListener(this);
        setBbWeman.setOnClickListener(this);
        setBbMan.setOnClickListener(this);
        setShengri.setOnClickListener(this);
        hyState.setOnClickListener(this);
        setBbTz.setOnClickListener(this);
        setBbSg.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                this.finish();
                break;
            case R.id.date:
                showDialog(DATE_DIALOG);
                break;
            case R.id.right_tv:
                Map<String, String> loginParams = new HashMap<>();
                switch (state) {
                    case 1:
                        loginParams.put("babyBirthday", date.getText().toString().trim());
                        loginParams.put("babySex", bb_sex);
                        loginParams.put("state", "3");
                        break;
                    case 2:
                        loginParams.put("babyExceptedBirthday", date.getText().toString().trim());
                        loginParams.put("state", "2");
                        break;
                    case 3:
                        loginParams.put("state", "1");
                        break;
                    case 4:
                        loginParams.put("babyExceptedBirthday", date.getText().toString().trim());
                        loginParams.put("state", "2");
                        break;
                    case 5:
                        loginParams.put("babyNickname", setBbName.getText().toString().trim());
                        loginParams.put("babyBirthday", setShengri.getText().toString().trim());
                        loginParams.put("babySex", bb_sex);
                        loginParams.put("babyBirthWeight", setBbSg.getText().toString().trim());
                        loginParams.put("babyBirthHeight", setBbTz.getText().toString().trim());
                        loginParams.put("state", "3");
                        break;
                    default:
                        break;
                }
                loginParams.put("userNo", share.getString("userno", ""));
                bangdingAPI(loginParams);

                break;
            case R.id.hy_recompose:
                if (state == 4) {
                    hyState.setVisibility(View.VISIBLE);
                }
                setHyzTime.setVisibility(View.GONE);
                setTime.setVisibility(View.VISIBLE);
                stateTitle.setText("您的预产期");
                uiTitle.setText("我的宝宝");
                date.setText(user.getBabyExceptedBirthday());
                break;
            case R.id.by_recompose:
                Intent go_set_state = new Intent(this, Set_yunyu.class);
                startActivity(go_set_state);
                this.finish();
                break;
            case R.id.hy_state:
                Intent go_set_states = new Intent(this, Set_yunyu.class);
                startActivity(go_set_states);
                this.finish();
                break;
            case R.id.bbsr_recompose:
                setYybbTime.setVisibility(View.GONE);
                uiTitle.setText("设置宝宝信息");
                rightTv.setVisibility(View.VISIBLE);
                setBbInfo.setVisibility(View.VISIBLE);
                hyState.setVisibility(View.VISIBLE);
                userState.setText("已有宝宝");
                break;
            case R.id.set_bb_weman:
                bb_sex = "0";
                break;
            case R.id.set_bb_man:
                bb_sex = "1";
                break;
            case R.id.set_shengri:
                final Calendar sr = Calendar.getInstance();
                mYear = sr.get(Calendar.YEAR);
                mMonth = sr.get(Calendar.MONTH);
                mDay = sr.get(Calendar.DAY_OF_MONTH);
                showDialog(DATE_DIALOG);
                break;
            case R.id.set_bb_sg:
                or = true;
                initSG();
                ShowPickerView();
                break;
            case R.id.set_bb_tz:
                or = false;
                initTZ();
                ShowPickerView();
                break;
            default:
                break;
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_DIALOG:
                return new DatePickerDialog(this, mdateListener, mYear, mMonth, mDay);
        }
        return null;
    }

    /**
     * 设置日期 利用StringBuffer追加
     */
    public void display() {
        String mday;
        String mmonth;
        if (mDay < 10) {
            mday = "0" + mDay;
        } else {
            mday = mDay + "";
        }

        if (mMonth + 1 < 10) {
            mmonth = "0" + (mMonth + 1);
        } else {
            mmonth = mMonth + 1 + "";
        }
        if (state == 5) {
            setShengri.setText(new StringBuffer().append(mYear).append("年").append(mmonth).append("月").append(mday).append("日"));
        } else {
            date.setText(new StringBuffer().append(mYear).append("年").append(mmonth).append("月").append(mday).append("日"));
        }
    }

    private DatePickerDialog.OnDateSetListener mdateListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            display();
        }
    };

    /**
     * 选择体重身高
     */
    private ArrayList<String> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();

    private void ShowPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                if (or) {
                    setBbSg.setText(options1Items.get(options1) + options2Items.get(options1).get(options2));
                } else {
                    setBbTz.setText(options1Items.get(options1) + options2Items.get(options1).get(options2));
                }
                Log.e("当前选择", options1Items.get(options1) + options2Items.get(options1).get(options2));
            }
        })

//                .setTitleText("身高")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();

//        pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器
//        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initSG() {//初始化身高
        options1Items.clear();
        options2Items.clear();
        double ii = 0.0;
        DecimalFormat df = new DecimalFormat("#.0");
        ArrayList<String> shengao = new ArrayList<>();
        for (int i = 1; i < 81; i++) {
            options1Items.add(i + "");

            while (ii < 0.91) {
                shengao.add(df.format(ii) + "cm");
                ii = ii + 0.1;
            }
            ii = 0.0;
            options2Items.add(shengao);
        }
    }

    private void initTZ() {//初始化体重
        options1Items.clear();
        options2Items.clear();
        double ii = 0.0;
        DecimalFormat df = new DecimalFormat("#.0");
        ArrayList<String> shengao = new ArrayList<>();
        for (int i = 1; i < 10; i++) {
            options1Items.add(i + "");

            while (ii < 0.91) {
                shengao.add(df.format(ii) + "kg");
                ii = ii + 0.1;
            }
            ii = 0.0;
            options2Items.add(shengao);
        }
    }

    /**
     * 设置绑定
     */
    private void bangdingAPI(Map<String, String> loginParams) {
        up.show();
        ApiService.getInstance(this).SET_PERSONAL_GESTATION(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = JIECHU;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
//                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }


    /**
     * 查询
     */
    private void chaxunAPI(Map<String, String> loginParams) {
        up.show();
        ApiService.getInstance(this).QUERY_PERSONAL_GESTATION(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = CHAXUN;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }


}
